#!/usr/bin/env python
# coding=utf-8
'''
@Author: 以谁为师
@Website: attacker.club
@Date: 2020-04-24 15:27:19
LastEditTime: 2021-05-31 21:44:46
@Description:
'''

import jinja2
import smtplib
from email.header import Header
from email.mime.text import MIMEText
from email.utils import formataddr
from datetime import datetime
now = datetime.now().strftime('%Y年%m月%d日 %H:%M:%S')

RENDER_HTML_TEMPLATE = """<html>
<head>
  <style type="text/css">
        body {
            font: 18px/1.5 Helvetica Neue, Helvetica, Arial, Microsoft Yahei, Hiragino Sans GB, Heiti SC, WenQuanYi Micro Hei, sans-serif;
        }

        div>div {
            color: blue;
        }
        .code{
            font-size: 12px;
            color: red;
        }

         ul {
            background-color: black;
        }

        ul>li {
            list-style: none;
            font-size: 20px;
            color: white;
        }
    </style>

</head>
<body>

    <h2>{{title}}</h2>
    
    <p> {{results.time}} </p>
    <p> {{results.text}} </p>
   

</body>
</html>
"""


def template(data):
    res = jinja2.Template(source=RENDER_HTML_TEMPLATE).render(results=data)
    return res


results = {'title': '自动任务',
           'time': now,
           'text': '测试'}


def send(From, email, password, smtp, results):
    html = template(results)
    mail_sender = email    # 发件人邮箱账号
    mail_pass = password              # 发件人邮箱密码
    mail_user = From      # 收件人邮箱账号，我这边发送给自己
    ret = True
    try:
        #msg = MIMEText(html, 'html', 'utf-8')
        msg = MIMEMultipart(html, 'html', 'utf-8')
        # 括号里的对应发件人邮箱昵称、发件人邮箱账号
        msg['From'] = formataddr(["robot", mail_sender])
        # 括号里的对应收件人邮箱昵称、收件人邮箱账号
        msg['To'] = formataddr(['To', mail_user])
        print(msg['To'])
        # msg['Cc'] = formataddr(['cc', mail_cc])  # 抄送

        msg['Subject'] = "邮件发送测试demo"                # 邮件的主题，也可以说是标题

        # 构造附件1，传送当前目录下的 test.txt 文件
        att1 = MIMEText(open('杭州05-31.xlsx', 'rb').read(), 'base64', 'utf-8')
        att1["Content-Type"] = 'application/octet-stream'
        # 这里的filename可以任意写，写什么名字，邮件中显示什么名字
        att1["Content-Disposition"] = 'attachment; filename="杭州05-31.xlsx"'
        msg.attach(att1)

        server = smtplib.SMTP_SSL(smtp, 465)  # 发件人邮箱中的SMTP服务器，端口是25
        server.login(mail_sender, mail_pass)  # 括号中对应的是发件人邮箱账号、邮箱密码
        # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件
        res = server.sendmail(
            mail_sender, [mail_user], msg.as_string())

        # print(res)
        # print(mail_user)
        server.quit()  # 关闭连接
    except Exception:  # 如果 try 中的语句没有执行，则会执行下面的 ret=False
        print("发送失败")
        ret = False

    return ret


if __name__ == '__main__':
    host = "imap.exmail.qq.com"
    email = "jjli@seedien.com"
    password = "xxxxxx"
    smtp = "smtp.exmail.qq.com"
    mail_from = "admin@attacker.club"
    send(mail_from, email, password, host, results)
